package com.example.demo.Util.redisUtil;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.core.CollectionUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

@Service
public class RedisServiceImpl implements RedisService{


    /** 释放锁lua脚本 */
    private static final String RELEASE_LOCK_LUA_SCRIPT = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";

    private static final String LOCK_SECKILL_KEY = "secKill_Lock_";
    private static final String userId = "123456";
    private static final Long  OUT_TIME = 500L;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;


    @Override
    public boolean TryGetLock(String requsetid,int courseid) {

        try {
            Long start = System.currentTimeMillis();
            while (true){
                Boolean result = redisTemplate.opsForValue().setIfAbsent(LOCK_SECKILL_KEY+courseid,requsetid,15, TimeUnit.SECONDS);
                if(result){
                    return true;
                }
                Long end = System.currentTimeMillis()-start;
                if( end >  OUT_TIME){
                    return false;
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
      return  false;
    }

    @Override
    public boolean UnLock(String requsetid, int courseid) {

        DefaultRedisScript redisScript =     new DefaultRedisScript<>(RELEASE_LOCK_LUA_SCRIPT,Long.class);

          Long res = (Long) redisTemplate.execute(redisScript, Collections.singletonList(LOCK_SECKILL_KEY+courseid),requsetid);
        System.out.println(res);
        if(res != 0){
            return true;
        }

        return false;
    }


}
